﻿using AutoMapper;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.SignalR;
using TrackSystem.Contracts;
using TrackSystem.Entities.Dtos.Slave;
using TrackSystem.Entities.Models;

namespace TrackSystem.API.SignalRHub;

/// <summary>
/// 从站操作SignalR服务
/// </summary>
/// <param name="wrapper"></param>
/// <param name="mapper"></param>
public class SlaveHelperHub(IRepositoryWrapper wrapper, IMapper mapper): Hub
{

    /// <summary>
    /// 获取所有从站信息
    /// </summary>
    /// <returns></returns>
    public async Task GetAllAsync()
    {
        var entities = await wrapper.Slave.GetAllListAsync();
        var dtos = mapper.Map<IEnumerable<SlaveDto>>(entities);
        await Clients.Caller.SendAsync("ReceiveAllSlave", dtos);
    }

    /// <summary>
    /// 获取所有从站信息
    /// </summary>
    /// <returns></returns>
    public async Task GetSlaveByIndex(int index)
    {
        var entities = await wrapper.Slave.GetAllListAsync();
        var dtos = mapper.Map<IEnumerable<SlaveDto>>(entities).ToList();
        if (index >= 0 && index < dtos.Count())
        {
            await Clients.Caller.SendAsync("ReceiveSlaveByIndex", dtos[index]);
            return;
        }

        await Clients.Caller.SendAsync("ReceiveSlaveByIndex", null);
    }

    /// <summary>
    /// 更新从站信息
    /// </summary>
    /// <param name="slave"></param>
    /// <returns></returns>
    public async Task SaveSlaveAsync(SlaveDto slave)
    {
        var result = await wrapper.Slave.UpdateSlaveAsync(slave);
        if (result is { Success: true, Data: not null })
        {
            await wrapper.Var.UpdateBaseSlave(result.Data);
        }
        await Clients.Caller.SendAsync("HandleSaveSlave", result);
    }

    /// <summary>
    /// 新增从站信息
    /// </summary>
    /// <param name="slave"></param>
    public async Task InsertSlaveAsync(SlaveDto slave)
    {
        var result = await wrapper.Slave.AddSlaveAsync(slave);
        if (result is { Success: true, Data: not null })
        {
            await wrapper.Var.UpdateBaseSlave(result.Data);
        }
        await Clients.Caller.SendAsync("HandleSaveSlave", result);     
    }
    
    /// <summary>
    /// 获取所有的变量名称
    /// </summary>
    /// <returns></returns>
    public async Task GetVarNames()
    {
        var regs = await wrapper.Var.GetAllListAsync();
        var names = regs.Select(reg => reg.Name).ToList();
        await Clients.Caller.SendAsync("RevVarNames", names);
    }

}